package com.wzw.springboot.principle.mvc.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HandlerInterceptor 拦截器，在 DispatcherServlet 执行 doDispatcher 方法时执行所有此接口的方法。达到请求拦截效果
 * 无法拦截原生的Servlet请求，因为原生的请求不会走到 DispatcherServlet 中
 * <p>
 * MappedInterceptor：HandlerInterceptor的子类，也是对它的包装。内部包含了一个 HandlerInterceptor 对象，赋予按照path拦截的能力
 * <p>
 * 初始化时机：也是在 WebMvcConfigurationSupport 配置类中，getInterceptors 方法，其具体的实现被到了子类。然后被包装成 MappedInterceptor
 * （DelegatingWebMvcConfiguration -> WebMvcConfigurerComposite -> WebMvcConfigurer ）
 *
 * @author Wangzhiwen
 */
public class CustomizedInterceptorOne implements HandlerInterceptor {

    /**
     * 前置拦截
     *
     * @param request  httRequest
     * @param response httpResponse
     * @param handler  处理器
     * @return true 放行 false 不放行
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 执行controller方法后回调
     *
     * @param request      httRequest
     * @param response     httpResponse
     * @param handler      处理器
     * @param modelAndView 执行方法后的返回的视图对象
     * @throws Exception 异常
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 方法执行完成后的拦截，不管执行结果是成功还是失败
     *
     * @param request  httRequest
     * @param response httpResponse
     * @param handler  处理器
     * @param ex       执行过程异常时被抛出的异常对象
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
